package dao

import (
	"context"
	"sale-admin/internal/models"

	"gorm.io/gorm"
)

type OrderShipmentInfo struct{}

func (OrderShipmentInfo) Set(
	ctx context.Context,
	db *gorm.DB,
	outTradeNO, // 交易号
	expressCom, // 快递公司
	expressNum,
	salt string, // 快递单号
) bool {
	rowsAffected := db.WithContext(ctx).Model(&models.OrderShipmentInfo{}).
		Where("out_trade_no = ?", outTradeNO).
		Updates(&models.OrderShipmentInfo{
			ExpressCom: expressCom,
			ExpressNum: expressNum,
			Salt:       salt,
		}).RowsAffected
	return rowsAffected == 1
}

func (OrderShipmentInfo) Get(
	ctx context.Context,
	db *gorm.DB,
	outTradeNO string, // 交易号
) models.OrderShipmentInfo {
	var record models.OrderShipmentInfo
	db.WithContext(ctx).Model(&models.OrderShipmentInfo{}).
		Where("out_trade_no = ?", outTradeNO).
		Take(&record)
	return record
}

// 物流详情
func (OrderShipmentInfo) Detail(
	ctx context.Context,
	db *gorm.DB,
	outTradeNO string, // 交易号
	expressCom, // 快递公司
	expressNum string, // 快递单号
) *models.OrderShipmentInfo {
	var record models.OrderShipmentInfo
	tx := db.WithContext(ctx).Model(&models.OrderShipmentInfo{})
	if outTradeNO != "" {
		tx = tx.Where("out_trade_no = ?", outTradeNO)
	}
	if expressCom != "" {
		tx = tx.Where("express_com = ?", expressCom)
	}
	if expressNum != "" {
		tx = tx.Where("express_num = ?", expressNum)
	}
	rowsAffected := tx.Take(&record).RowsAffected
	if rowsAffected <= 0 {
		return nil
	}
	return &record
}
